package net.muchine.test.ddd.domain.order;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;

import net.muchine.test.ddd.domain.Money;
import net.muchine.test.ddd.domain.Product;
import net.muchine.test.ddd.repository.ProductRepository;

@Configurable(preConstruction=true)
public class OrderLineItem {
	private Long id;
	private Product product;
	private int quantity;
	
	@Autowired private ProductRepository productRepository;
	
	public OrderLineItem() {}
	
	public OrderLineItem(String productName, int quantity) {
		this.product = productRepository.find(productName);
		this.quantity = quantity;
	}

	public Money getPrice() {
		return product.getPrice().multiply(quantity);
	}
	
	public Product getProduct() {
		return product;
	}

	public int getQuantity() {
		return quantity;
	}

	public boolean isProductEqual(OrderLineItem lineItem) {
		return product == lineItem.product;
	}

	public OrderLineItem merge(OrderLineItem lineItem) {
		this.quantity += lineItem.quantity;
		return this;
	}

	@Override
	public boolean equals(Object object) {
		if (object == this) return true;
		
		if (!(object instanceof OrderLineItem)) return false;
		
		final OrderLineItem item = (OrderLineItem) object;
		return this.product.equals(item.getProduct()) && this.quantity == item.getQuantity();
	}
	
	@Override
	public int hashCode() {
		int result = 17;
		result = 37 * result + this.product.hashCode();
		result = 37 * result + this.quantity;
		
		return result;
	}	
}
